package com.ning.activitys.skysound.fragment.musicpavilion;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.google.gson.Gson;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.ning.activitys.skysound.R;
import com.ning.activitys.skysound.activity.MainActivity;
import com.ning.activitys.skysound.adpter.MyGridViewAdapter;
import com.ning.activitys.skysound.base.BaseFragment;
import com.ning.activitys.skysound.base.MyApplication;
import com.ning.activitys.skysound.beans.GsonFindMusic;
import com.ning.activitys.skysound.beans.GsonRadioDetails;
import com.ning.activitys.skysound.beans.GsonRadio;
import com.ning.activitys.skysound.beans.NativeInformationBeans;
import com.ning.activitys.skysound.service.PlayService;
import com.ning.activitys.skysound.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dllo on 16/1/8.
 */
public class RadioFragment extends BaseFragment implements ExpandableListView.OnChildClickListener{

    private MainActivity mainActivity;
    private ExpandableListView expandableListView;
    private RadioAdapter adapter;
    private GsonRadio gsonRadio;
    private GsonRadioDetails gsonRadioDetails;
    private MyApplication myApplication;
    private List<GsonRadio.DataEntity.DataEntity1> childData;

    public int myGroupPosition, myChildPosotion;

    public int getMyGroupPosition() {
        return myGroupPosition;
    }

    public void setMyGroupPosition(int myGroupPosition) {
        this.myGroupPosition = myGroupPosition;
    }

    public int getMyChildPosotion() {
        return myChildPosotion;
    }

    public void setMyChildPosotion(int myChildPosotion) {
        this.myChildPosotion = myChildPosotion;
    }


    private NativeInformationBeans nativeInformation = new NativeInformationBeans();

    private ArrayList<String> songsUrl = new ArrayList<>();

    private String url = "http://api.fm.ttpod.com/radio?app=ttpo" +
            "d&v=v8.1.4.2016011318&user_id=0&mid=iPhone5S&f=f320&s=s31" +
            "0&imsi=&hid=&splus=9.2&active=1&net=2&openudid=1320e380b9b2" +
            "f879587531a841bd2709b0fe0b43&idfa=1797AE83-E11D-40E8-BF4A-51688F9D8197&utdid=VcqZd7Bai40DA" +
            "KYNvRHg4TLh&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude=";

    private String urlSong = "http://api.fm.ttpod.com/radiosong?num=150&tagid=8&app=ttpod&v=v8.1.4.201601" +
            "1318&user_id=0&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=9.2&active=1&net=2&openudid=1320e" +
            "380b9b2f879587531a841bd2709b0fe0b43&idfa=1797AE83-E11D-40E8-BF4A-51688F9D8197&utdid=VcqZd7Bai" +
            "40DAKYNvRHg4TLh&alf=201200&bundle_id=com.ttpod.music&latitude=&longtitude=";

    private int Tagid;

    private volatile static RadioFragment radioFragment;//单例的引用
    //单例模式创建对象
    public static RadioFragment getInstance() {
        if (radioFragment == null) {
            //线程锁,只有一个线程可以调用
            synchronized (RadioFragment.class) {
                if (radioFragment == null) {
                    radioFragment = new RadioFragment();
                }
            }
        }
        return radioFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_mp_recommended, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        expandableListView = (ExpandableListView) view.findViewById(R.id.expand_list_view_recommended_fragment);

        expandableListView.setOnChildClickListener(this);

        myApplication = (MyApplication) mainActivity.getApplication();


        getData();


    }

    /**
     * 获得本页数据
     */
    private void getData() {
        final Gson gson = new Gson();
        VolleySingleton.addRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                gsonRadio = gson.fromJson(response, GsonRadio.class);


                adapter = new RadioAdapter();
                expandableListView.setAdapter(adapter);


                int groupCount = expandableListView.getCount();

                for (int i = 0; i < groupCount; i++) {

                    expandableListView.expandGroup(i);

                }

                expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
                    @Override
                    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                        return true;
                    }
                });


                expandableListView.setGroupIndicator(null);

                /**
                 *  向数据库中存储
                 * */
                nativeInformation.setName("radio");
                nativeInformation.setContent(response);

                try {
                    NativeInformationBeans nativeInformationBeans =
                            myApplication.dbUtils.findFirst(Selector.from(NativeInformationBeans.class).where("name", "=", "radio"));

                    if (null == nativeInformationBeans) {

                        myApplication.dbUtils.save(nativeInformation);
                    } else {
                        myApplication.dbUtils.update(nativeInformation, "content");
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                try {

                    NativeInformationBeans nativeInformationBeans =
                            myApplication.dbUtils.findFirst(Selector.from(NativeInformationBeans.class).where("name", "=", "radio"));

                    gsonRadio = gson.fromJson(nativeInformationBeans.getContent(), GsonRadio.class);

                    adapter = new RadioAdapter();
                    expandableListView.setAdapter(adapter);

                    expandableListView.setGroupIndicator(null);

                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    /**
     * 获取本页网络音乐
     */
    public void getRadioSong(){

        PlayService.IS_NET_MUSIC = 0;

        mainActivity.playService.setSkySoundListType(PlayService.RADIO_TYPE);

        Tagid = gsonRadio.getData().get(myGroupPosition).getData().get(myChildPosotion).getTag_id();

        final Gson gson = new Gson();

        String thisUrlSong = urlSong.replace("tagid=8", "tagid=" + Tagid);

        VolleySingleton.addRequest(thisUrlSong, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                gsonRadioDetails = gson.fromJson(response, GsonRadioDetails.class);

                mainActivity.playService.setGsonRadioDetails(gsonRadioDetails);

//                if (gsonRadioDetails.getData().size() != 0) {
//
//                        songBeans.setTitle(gsonRadioDetails.getData().get(0).getSong_name());
//                        songBeans.setSingerName(gsonRadioDetails.getData().get(0).getSinger_name());
//                        songBeans.setDuration(gsonRadioDetails.getData().get(0).getUrl_list().get(0).getDuration());

                // mainActivity.playService.setSongBeans(songBeans);

                mainActivity.playService.playNet(gsonRadioDetails.getData().get(0).getUrl_list().get(0).getUrl(), myGroupPosition);


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(mainActivity, "没网点个屁", Toast.LENGTH_SHORT).show();

            }
        });


    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

        Toast.makeText(mainActivity, groupPosition+"saaaaa", Toast.LENGTH_SHORT).show();
        return false;
    }



    /**
     * 内部类 适配器
     */

    private class RadioAdapter extends BaseExpandableListAdapter {

        @Override
        public int getGroupCount() {
            return gsonRadio.getData().size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return 1;
        }

        @Override
        public Object getGroup(int groupPosition) {
            return null;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return null;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }


        /*
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupViewHolder groupViewHolder;
            if (convertView == null){
                convertView = LayoutInflater.from(mainActivity).inflate(R.layout.item_rv_group_radio,parent,false);
                groupViewHolder = new GroupViewHolder(convertView);
                convertView.setTag(groupPosition);
            }else {

                groupViewHolder = (GroupViewHolder) convertView.getTag();
            }
            groupViewHolder.group.setText(gsonRadio.getData().get(groupPosition).getTag_type_name());

            return convertView;
        }*/


        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            GroupViewHolder groupViewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mainActivity).inflate(R.layout.item_rv_group_radio, parent, false);
                groupViewHolder = new GroupViewHolder(convertView);
                convertView.setTag(groupViewHolder);
            } else {
                groupViewHolder = (GroupViewHolder) convertView.getTag();
            }
            groupViewHolder.group.setText(gsonRadio.getData().get(groupPosition).getTag_type_name());
            return convertView;
        }


        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ChildViewHolder childViewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(mainActivity).inflate(R.layout.item_grid_view, parent, false);
                childViewHolder = new ChildViewHolder(convertView);
                convertView.setTag(childViewHolder);
            } else {
                childViewHolder = (ChildViewHolder) convertView.getTag();
            }

            if (null != gsonRadio){

                childData = gsonRadio.getData().get(groupPosition).getData();

                MyGridViewAdapter gridViewAdapter = new MyGridViewAdapter(mainActivity,childData);
                childViewHolder.gridView.setAdapter(gridViewAdapter);

                childViewHolder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                        setMyChildPosotion(position);
                        setMyGroupPosition(groupPosition);

                        getRadioSong();


                    }
                });

            }


            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }


        private class GroupViewHolder {
            private TextView group;

            public GroupViewHolder(View view) {
                group = (TextView) view.findViewById(R.id.tv_rv_group_radio);
            }
        }

        //        private class ChildViewHolder {
//            private NetworkImageView childImage;
//            private TextView radioSongTypeChild,radioSongSizeChild;
//
//            public ChildViewHolder(View view) {
//                childImage = (NetworkImageView) view.findViewById(R.id.iv_rv_child_image_radio);
//                radioSongSizeChild = (TextView) view.findViewById(R.id.tv_radio_song_size);
//                radioSongTypeChild = (TextView) view.findViewById(R.id.tv_radio_song_type);
//            }
//        }
        private class ChildViewHolder {

            private GridView gridView;
            public ChildViewHolder(View view){

                gridView = (GridView) view.findViewById(R.id.item_gridView);
            }
        }

    }

}
